<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use Prettus\Validator\Contracts\ValidatorInterface;
use Prettus\Validator\Exceptions\ValidatorException;
use App\Http\Requests\ElectricFeeTypeCreateRequest;
use App\Http\Requests\ElectricFeeTypeUpdateRequest;
use App\Repositories\ElectricFeeTypeRepository;
use App\Validators\ElectricFeeTypeValidator;

/**
 * Class ElectricalFeeTypesController.
 *
 * @package namespace App\Http\Controllers;
 */
class ElectricFeeTypesController extends Controller
{
    /**
     * @var ElectricFeeTypeRepository
     */
    protected $repository;

    /**
     * @var ElectricFeeTypeValidator
     */
    protected $validator;

    /**
     * ElectricalFeeTypesController constructor.
     *
     * @param ElectricFeeTypeRepository $repository
     * @param ElectricFeeTypeValidator $validator
     */
    public function __construct(ElectricFeeTypeRepository $repository, ElectricFeeTypeValidator $validator)
    {
        $this->repository = $repository;
        $this->validator  = $validator;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $this->repository->pushCriteria(app('Prettus\Repository\Criteria\RequestCriteria'));
        $electricFeeTypes = $this->repository->all();
        \request()->flash();
        if (request()->wantsJson()) {

            return response()->json([
                'data' => $electricFeeTypes,
            ]);
        }

        return view('electricFeeTypes.index', compact('electricFeeTypes'));
    }

    public function create(){
        return view('electricFeeTypes.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  ElectricFeeTypeCreateRequest $request
     *
     * @return \Illuminate\Http\Response
     *
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    public function store(ElectricFeeTypeCreateRequest $request)
    {
        try {

            $this->validator->with($request->all())->passesOrFail(ValidatorInterface::RULE_CREATE);

            if($request->get('season_control')){
                $month_overlap=false;
                $sameTypes = $this->repository->findWhere(['name'=>$request->get('name')]);
                $from_month = $request->get('from_month');
                $to_month = $request->get('to_month');
                foreach ($sameTypes as $sameType){
                    if($from_month<=$sameType->from_month && $to_month>=$sameType->to_month){
                        $month_overlap=true;
                        break;
                    }
                    if($from_month>=$sameType->from_month && $from_month<=$sameType->to_month){
                        $month_overlap = true;
                        break;
                    }
                    if($to_month>=$sameType->from_month && $to_month<=$sameType->to_month){
                        $month_overlap = true;
                        break;
                    }
                }
                if($month_overlap){
                    if ($request->wantsJson()) {
                        return response()->json([
                            'error'   => true,
                            'message' => "同组电费类型中起止月份发生了重叠"
                        ]);
                    }
                    return redirect()->back()->withErrors("同组电费类型中起止月份发生了重叠")->withInput();
                }
            }
            if($request->get('level_control')){
                $level_overlap=false;
                $sameTypes = $this->repository->findWhere(['name'=>$request->get('name')]);
                $level_from = $request->get('level_from');
                $level_to = $request->get('level_to');
                foreach ($sameTypes as $sameType){
                    if($level_from<=$sameType->level_from && $level_to>=$sameType->level_to){
                        $level_overlap=true;
                        break;
                    }
                    if($level_from>$sameType->level_from && $level_from<=$sameType->level_to){
                        $level_overlap=true;
                        break;
                    }
                    if($level_to>$sameType->level_from && $level_to<=$sameType->level_to){
                        $level_overlap=true;
                        break;
                    }
                }
                if($level_overlap){
                    if ($request->wantsJson()) {
                        return response()->json([
                            'error'   => true,
                            'message' => "同组电费类型中分级范围重叠"
                        ]);
                    }
                    return redirect()->back()->withErrors("同组电费类型中分级范围重叠")->withInput();
                }
            }
            $electricFeeType = $this->repository->create($request->all());

            $response = [
                'message' => 'ElectricalFeeType created.',
                'data'    => $electricFeeType->toArray(),
            ];

            if ($request->wantsJson()) {

                return response()->json($response);
            }

            return redirect()->back()->with('message', $response['message']);
        } catch (ValidatorException $e) {
            if ($request->wantsJson()) {
                return response()->json([
                    'error'   => true,
                    'message' => $e->getMessageBag()
                ]);
            }

            return redirect()->back()->withErrors($e->getMessageBag())->withInput();
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $electricFeeType = $this->repository->find($id);

        if (request()->wantsJson()) {

            return response()->json([
                'data' => $electricFeeType,
            ]);
        }

        return view('electricFeeTypes.show', compact('electricFeeType'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $electricFeeType = $this->repository->find($id);

        return view('electricFeeTypes.edit', compact('electricFeeType'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  ElectricFeeTypeUpdateRequest $request
     * @param  string            $id
     *
     * @return Response
     *
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    public function update(ElectricFeeTypeUpdateRequest $request, $id)
    {
        try {
            $this->validator->with($request->all())->passesOrFail(ValidatorInterface::RULE_UPDATE);
            $electricFeeType = $this->repository->update($request->all(), $id);

            $response = [
                'message' => 'ElectricalFeeType updated.',
                'data'    => $electricFeeType->toArray(),
            ];

            if ($request->wantsJson()) {
                return response()->json($response);
            }

            return redirect()->back()->with('message', $response['message']);
        } catch (ValidatorException $e) {

            if ($request->wantsJson()) {

                return response()->json([
                    'error'   => true,
                    'message' => $e->getMessageBag()
                ]);
            }

            return redirect()->back()->withErrors($e->getMessageBag())->withInput();
        }
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if($this->repository->find($id)->dormTypes->count()){
            if (request()->wantsJson()) {

                return response()->json([
                    'error' => true,
                    'message' => '已经被引用，不能删除。',
                ]);
            }

            return redirect()->back()->withErrors('message', '已经被引用，不能删除。');
        }
        $deleted = $this->repository->delete($id);

        if (request()->wantsJson()) {

            return response()->json([
                'message' => 'ElectricalFeeType deleted.',
                'deleted' => $deleted,
            ]);
        }

        return redirect()->back()->with('message', 'ElectricalFeeType deleted.');
    }
}
